<script setup lang="tsx">
import { onMounted, ref } from 'vue';
import { Button, Popconfirm, Switch } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { destroyDevice, getDeviceListApi, requestDeviceControl, switchDevice } from '@/service/api/businessApi';
import { deviceHooks } from '@/views/breedingManage/deviceManage/deviceHooks';
import { getewayHooks } from '@/views/breedingManage/getewayManage/getewayHooks';
import { terminalHooks } from '@/views/breedingManage/terminalManage/terminalHooks';
import { useProjectStore } from '@/store/modules/project';
import { breedingPondManageHooks } from '@/views/breedingManage/breedingPondManage/breedingPondManageHooks';
import DeviceDetail from './modules/device-detail.vue';
import UserSearch from './modules/search.vue';
import UserOperateDrawer from './modules/operate-drawer.vue';
import ResetPeriod from './modules/reset-period.vue';

const { tableWrapperRef, scrollConfig } = useTableScroll();

const projectStore = useProjectStore();
const { getDeviceCategory, deviceCategoryList } = deviceHooks();
const { getGetewayList } = getewayHooks();
const { getHostList } = terminalHooks();
const { getFarmList } = breedingPondManageHooks();

const getewayData = ref([]);
const hostData = ref([]);
const farmData = ref([]);
onMounted(async () => {
  await getDeviceCategory({});
  getewayData.value = await getGetewayList(undefined);
  hostData.value = await getHostList({ projectId: projectStore.currentProject?.id });
  farmData.value = await getFarmList(projectStore.currentProject?.id);
});

/* 设备类别 */
const getDeviceType = (type: number) => {
  let typeText = '传感器';
  switch (type) {
    case 1:
      typeText = '传感器';
      break;
    case 2:
      typeText = '控制器';
      break;
    case 3:
      typeText = '复合型';
      break;
    default:
      typeText = '';
  }
  return typeText;
};

const statusChange = async (data: any) => {
  const res: any = switchDevice({
    id: data.id,
    status: data.status
  });
  if (res.code === 200) {
    window.$message?.success(data.deviceType === 1 ? '设备（传感器）更新状态成功！' : '设备（控制器）更新状态成功！');
  } else {
    window.$message?.error(
      res.message || (data.deviceType === 1 ? '设备（传感器）更新状态失败！' : '设备（控制器）更新状态失败！')
    );
  }
};

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: getDeviceListApi,
  apiParams: {
    pageNo: 1,
    pageSize: 10,
    parentId: 0,
    projectId: projectStore.currentProject?.id
  },
  columns: (): any => [
    {
      key: 'hostName',
      dataIndex: 'hostName',
      title: '终端名称',
      align: 'center',
      width: 180,
      fixed: 'left'
    },
    {
      key: 'collectionName',
      dataIndex: 'collectionName',
      title: '网关名称',
      align: 'center',
      width: 160
    },
    {
      key: 'deviceName',
      title: '设备名称',
      dataIndex: 'deviceName',
      align: 'center',
      width: 160
    },
    {
      title: '设备编号',
      dataIndex: 'deviceNo',
      key: 'deviceNo',
      align: 'center',
      width: 160
    },
    {
      title: '设备类别',
      dataIndex: 'deviceType',
      key: 'deviceType',
      align: 'center',
      width: 160,
      customRender: ({ record }: any) => {
        return getDeviceType(record.deviceType);
      }
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      align: 'center',
      width: 160
    },
    {
      title: '养殖池',
      dataIndex: 'farmId',
      key: 'farmId',
      align: 'center',
      width: 160,
      customRender: ({ record }: any) => {
        return farmData.value.find((item: any) => item.id === record.farmId)?.name;
      }
    },
    {
      title: '当前值',
      dataIndex: 'field',
      key: 'field',
      align: 'center',
      width: 160
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      align: 'center',
      width: 160
    },
    {
      title: '阈值范围',
      dataIndex: 'between',
      key: 'between',
      align: 'center',
      width: 160,
      customRender: ({ record }: any) => {
        if (record.deviceType === 1) return `${record.lowAlarm || ''} - ${record.hiAlarm || ''}`;
        return '';
      }
    },
    {
      title: '周期',
      dataIndex: 'period',
      key: 'period',
      align: 'center',
      width: 160,
      customRender: ({ record }: any) => {
        if (record.deviceType === 1) return record.period;
        return '';
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 160,
      customRender: ({ record }: any) => {
        if (record.status !== undefined) {
          return (
            <Switch
              disabled
              checked={record.status}
              checked-children="开启"
              un-checked-children="关闭"
              onChange={() => statusChange(record)}
            />
          );
        }
        return '';
      }
    },
    {
      title: '终端编码',
      dataIndex: 'hostNo',
      key: 'hostNo',
      align: 'center',
      width: 160
    },
    {
      title: '网关编码',
      dataIndex: 'collectionNo',
      key: 'collectionNo',
      align: 'center',
      width: 160
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      align: 'center',
      width: 160
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      fixed: 'right',
      customRender: ({ record }: any) => (
        <div class="flex-center gap-8px">
          {['1000', '2000'].includes(String(record.categoryCode)) && record.parentId === 0 && (
            <Button type="primary" ghost size="small" onClick={() => addchildren(record)}>
              添加
            </Button>
          )}
          {record.deviceType === 3 && record.parentId !== 0 && (
            <Button type="primary" ghost size="small" onClick={() => handleSwitch(record)}>
              动作按钮
            </Button>
          )}
          {record.deviceType === 1 && (
            <Button type="primary" ghost size="small" onClick={() => resetPeriod(record)}>
              重置周期
            </Button>
          )}
          {!['1000', '2000'].includes(String(record.categoryCode)) && (
            <Button type="primary" ghost size="small" onClick={() => showDetail(record)}>
              详情
            </Button>
          )}
          <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.id)}>
            <Button danger size="small">
              删除
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  checkedRowKeys,
  onDeleted,
  openDrawer
  // closeDrawer
} = useTableOperate(data as any, getData);

async function handleDelete(id: any) {
  const res = await destroyDevice(id);
  if (res.error === null) await onDeleted();
}

const DeviceDetailRef = ref();

function showDetail(rowData: any) {
  DeviceDetailRef.value?.setRowData(rowData);
}

const ResetPeriodRef = ref();
const resetPeriod = (rowData: any) => {
  ResetPeriodRef.value?.setRowData(rowData);
};

function addchildren(record: any) {
  operateType.value = 'addChild';
  editingData.value = cloneDeep({
    parentId: record.id,
    deviceType: record.deviceType === 3 ? 2 : record.deviceType
  } as any);
  openDrawer();
}

const handleSwitch = (row: any) => {
  requestDeviceControl({
    id: row.id
  }).then((res: any) => {
    if (res.code === 200) {
      window.$message?.success('操作成功');
    }
  });
};

const changeDeviceType = async (val: any) => {
  await getDeviceCategory({ deviceType: val });
};
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch
      v-model:model="searchParams"
      v-model:deviceCategoryList="deviceCategoryList"
      v-model:hostData="hostData"
      v-model:getewayData="getewayData"
      v-model:farmData="farmData"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <ACard
      title="设备列表"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :scroll="scrollConfig"
        :loading="loading"
        row-key="id"
        :pagination="mobilePagination"
        class="h-full"
        children-column-name="childDeviceInfo"
      />

      <UserOperateDrawer
        v-model:visible="drawerVisible"
        v-model:deviceCategoryList="deviceCategoryList"
        v-model:hostData="hostData"
        v-model:farmData="farmData"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
        @change-device-type="changeDeviceType"
      />

      <DeviceDetail
        ref="DeviceDetailRef"
        v-model:hostData="hostData"
        v-model:farmData="farmData"
        @submitted="getDataByPage"
      />
      <ResetPeriod ref="ResetPeriodRef" @refresh-table="getDataByPage" />
    </ACard>
  </div>
</template>

<style scoped></style>
